/**
 * 基于HTML5的头像控件
 * @author wugang@ygsoft.com
 * @date 2016/10/28
 */
define(["jquery", "ecp.component.dialog", "jquery.Jcrop"], function ($, dialog) {
    "use strict";
    var scope = {};
    //一个空文件对象
    var image = new Image();
    var $container = null;
    /**
     * 初始化动作
     * @param modal
     */
    function initAction(modal) {
        //使用模态窗提示工具
        scope.notify = modal.notify;
        $("#fileInput", $container).on("change", function (event) {
            var fileObj = event.target;
            readImgFile(fileObj);
        });
        $("#reUpload", $container).on('change', function (event) {
            var fileObj = event.target;
            readImgFile(fileObj);
        });
    }

    /**
     * 读取文件
     *  @param fileObj 当前文件对象
     */
    function readImgFile(fileObj) {
        if (!fileObj || !fileObj.files || fileObj.files.length == 0) {
            scope.notify('请选择文件');
            return;
        }
        var files = fileObj.files;
        var reg = /image.*/;
        if (!files[0].type.match(reg)) {
            scope.notify('请选择图片类型的文件');
            return;
        }
        showOrHide();
        var imgFile = files[0];
        var reader = new FileReader();
        reader.onload = function (event) {
            var imgSrc = reader.result;
            initImage(imgSrc);
            setImageURL(imgSrc);
        };
        reader.readAsDataURL(imgFile);
    }

    /**
     * 保存图片
     */
    function saveImgFile(serverUrl, callback) {
        //未裁剪图片上传原图
        var cropX = scope.cropX ? scope.cropX : 0,
            cropY = scope.cropY ? scope.cropY : 0,
            cropW = scope.cropW ? scope.cropW : $("#originalPic", $container).width(),
            cropH = scope.cropH ? scope.cropH : $("#originalPic", $container).height();
        //使用canvas绘图生成截取后的图片发送给服务端
        var canvas = $('<canvas width="' + cropW + '" height="' + cropH + '" style="display:none"></canvas>')[0];
        var ctx = canvas.getContext('2d');
        //开始绘画
        ctx.drawImage(image, cropX, cropY, cropW, cropH, 0, 0, cropW, cropH);
        var data = canvas.toDataURL();
        var fd = new FormData();
        fd.append('file', convertBase64UrlToBlob(data));
        //上传
        $.ajax({
            url: serverUrl,
            type: "POST",
            data: fd,
            processData: false,
            contentType: false,
            success: function (resp, statusText, jqXHR) {
            	//上传成功执行回调
            	$.isFunction(callback) && callback.call(null, resp);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console && console.error('Upload error.');
            }
        });
    }

    /**
     * base64编码转换成blob
     */
    function convertBase64UrlToBlob(urlData) {
        urlData = urlData.split(',')[1];
        urlData = window.atob(urlData);
        var ia = new Uint8Array(urlData.length);
        for (var i = 0; i < urlData.length; i++) {
            ia[i] = urlData.charCodeAt(i);
        }
        var blob = new Blob([ia], {type: "image/png"});
        return blob;
    }

    /**
     * 图片展示
     * @param imgSrc
     */
    function initImage(imgSrc) {
        var $imgs = $("img[class*='picture']", $container),
            imgsLen = $imgs.length,
            i = 0;
        if (imgsLen) {
            for (; i < imgsLen; i++) {
                $($imgs[i]).css({
                    width: 'auto',
                    height: 'auto'
                });
                $imgs[i].src = imgSrc;
            }
        }
        $imgs.on("load", function () {
            //对左侧大的预览图初始化截图器
            if (!--imgsLen) {
                initJCrop(scope);
            }
        });
    }

    /**
     * 生成截图器
     * @param scope
     */
    function initJCrop(scope) {
        //重新上传图片先销毁jcrop
        if (scope.jcrop_api) {
            scope.jcrop_api.destroy();
        }
        $(function () {
            //图片框尺寸
            var maxHeight = 450,
                maxWidth = 450,
            //编辑区图片尺寸
                BoundW,
                BoundH,
            //Jcrop编辑区
                $jcropHolder,
            //图像属性
                bigPic = {
                    width: 180,
                    height: 180,
                    img: $("#largePicture", $container)
                },
                middlePic = {
                    width: 90,
                    height: 90,
                    img: $("#middlePicture", $container)
                },
                smallPic = {
                    width: 60,
                    height: 60,
                    img: $("#smallPicture", $container)
                },
            //原图的宽高
                $originalPic = $("#originalPic", $container),
                originImgW = $originalPic.width(),
                originImgH = $originalPic.height(),
            //原图放在编辑区后缩放的比例
                scale;
            $('#previewPic').Jcrop({
                onChange: updatePreview,
                onSelect: updatePreview,
                onRelease: reSetCrop,
                aspectRatio: 1
            }, function () {
                var bounds = this.getBounds();
                BoundW = bounds[0];
                BoundH = bounds[1];
                $jcropHolder = $(".jcrop-holder");
                //居中显示
                if (BoundW < maxWidth || BoundH < maxHeight) {
                    $jcropHolder.css({
                        top: "50%",
                        left: "50%",
                        marginLeft: "-" + (BoundW / 2) + "px",
                        marginTop: "-" + (BoundH / 2) + "px"
                    });
                }
                //操作crop的api
                scope.jcrop_api = this;
                //编辑区图片相对于原图的比例
                scale = BoundW / originImgW;
                reSetCrop();
            });

            /**
             * 刷新预览
             * @param crop
             */
            function updatePreview(crop) {
                if (parseInt(crop.w) > 0) {
                    scope.cropX = Math.round(crop.x / scale);
                    scope.cropY = Math.round(crop.y / scale);
                    scope.cropW = Math.round(crop.w / scale);
                    scope.cropH = Math.round(crop.h / scale);
                    refreshView(bigPic, crop);
                    refreshView(middlePic, crop);
                    refreshView(smallPic, crop);
                }
            }

            /**
             * 释放选择框,重置并初始化数据
             */
            function reSetCrop() {
                scope.cropX = 0;
                scope.cropY = 0;
                scope.cropW = 0;
                scope.cropH = 0;
                //重置预览区
                originView(bigPic);
                originView(middlePic);
                originView(smallPic);
            }

            /**
             * 更新大中小三个图片框的图片显示
             **/
            function refreshView(picObj, crop) {
                //大中小显示框相对于编辑框的尺寸比例
                var rx = picObj.width / crop.w;
                var ry = picObj.height / crop.h;
                picObj.img.css({
                    width: Math.round(rx * BoundW) + 'px',
                    height: Math.round(ry * BoundH) + 'px',
                    marginLeft: '-' + Math.round(rx * crop.x) + 'px',
                    marginTop: '-' + Math.round(ry * crop.y) + 'px'
                });
            }
            //原图预览
            function originView(picObj) {
                picObj.img.css({
                    width: picObj.width,
                    height: picObj.height,
                    marginLeft: '0px',
                    marginTop: '0px'
                });
            }

        })
    }

    /**
     * 隐藏或展现按钮
     */
    function showOrHide() {
        $("#uploadDiv", $container).hide();
        $("#reUploadDiv", $container).show();
    }

    function setImageURL(url) {
        image.src = url;
    }

    /**
     * 渲染入口
     */
    function render(serverUrl, callback) {
    	pictureHtml = require("text!/grm/ecp/webcore/components/photoSetting/photoSetting.html");
        dialog.show({
            title: '照片设置',
            content: pictureHtml,
            width: "720px",
            height: "520px",
            dialogShow: function (modal) {
                $container = modal;
                initAction(modal);
            },
            showCloseButton: false,
            otherButtons: ["取消", "保存"],
            otherButtonStyles: ["btn-link", "btn-primary"],
            clickButton: function (sender, modal, index) {
                if (index === "1") {
                    saveImgFile(serverUrl, callback);
                }
                modal.modal('hide');
            },
            draggable: false
        });
    }

    return {
    	/**
    	 * @params serverUrl 上传的服务端地址
    	 * @params callback 上传成功后的回调
    	 */
        show: function (serverUrl, callback) {
        	if(serverUrl){
        		render(serverUrl, callback);
        	}
        }
    }
})
